package org.knight.gearbox.security;

import org.knight.gearbox.model.entity.UserRole;
import org.knight.gearbox.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRoleRepository roleRepository;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {

        AccessAware accessAware = (AccessAware) auth.getPrincipal();

        List<UserRole> userRoleList = roleRepository.findUserRolesByUserIdAndBuId(accessAware);

        List<GrantedAuthority> authorities = userRoleList.stream()
                .map(userRole -> new SimpleGrantedAuthority(userRole.getRole())).collect(Collectors.toList());
        return new UsernamePasswordAuthenticationToken(auth.getName(),
                auth.getCredentials(), authorities);

    }
}
